<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-refresh"
        @click="getList()"
      >
        刷新
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        :icon="expandAll ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
        @click="handleExpand()"
      >
        {{ expandAllTitle }}
      </el-button>
      <el-button
        v-has="hasButtons.addbutton"
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate()"
      >
        添加
      </el-button>
    </div>

    <tree-table
      v-loading="listLoading"
      :data="menuTree"
      :default-expand-all="expandAll"
      :columns="columns"
      border
      default-children="children"
    >
      <template slot="type" slot-scope="{ scope }">
        <span>{{ formatMenuType(scope.row) }}</span>
      </template>

      <template slot="operation" slot-scope="{ scope }">
        <el-button
          v-show="scope.row.type == 1"
          v-has="hasButtons.addsubbutton"
          type="primary"
          size="mini"
          icon="el-icon-plus"
          plain
          @click="handleCreate(scope.row)"
        >
          添加下级
        </el-button>
        <el-button
          v-has="hasButtons.editbutton"
          type="primary"
          size="mini"
          icon="el-icon-edit"
          plain
          @click="handleUpdate(scope.row)"
        >
          编辑
        </el-button>
        <cus-del-btn
          v-has="hasButtons.deletebutton"
          @ok="handleDelete(scope.row.id)"
        ></cus-del-btn>
      </template>
    </tree-table>

    <div class="dia">
      <el-dialog
        v-dialogDrag
        :visible.sync="dialogVisible"
        @close="handleDialogClose"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="my-sysmenu-add" />
            <span>{{ titleMap[dialogStatus] }}</span>
          </div>
        </template>
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="form"
          label-position="right"
          label-width="120px"
          style="margin-left: 50px; margin-right: 70px"
        >
          <el-form-item
            v-show="parseInt(form.level) != 1"
            :label="tempDesc.parentName"
            prop="parentName"
          >
            <el-input v-model="form.parentName" :placeholder="'无'" disabled />
          </el-form-item>
          <el-form-item :label="tempDesc.name" prop="name">
            <el-input
              v-model="form.name"
              :placeholder="'请输入' + tempDesc.name"
            />
          </el-form-item>
          <el-form-item :label="tempDesc.component" prop="component">
            <el-input
              v-model="form.component"
              :placeholder="'请输入' + tempDesc.component"
            />
          </el-form-item>
          <el-form-item :label="tempDesc.url" prop="url">
            <!--          <el-input v-model="form.url" :placeholder="'请输入' + tempDesc.url" :disabled="dialogStatus !='create'"/>-->
            <el-input
              v-model="form.url"
              :placeholder="'请输入' + tempDesc.url"
            />
          </el-form-item>

          <el-form-item :label="tempDesc.redirect" prop="redirect">
            <!--          <el-input v-model="form.url" :placeholder="'请输入' + tempDesc.url" :disabled="dialogStatus !='create'"/>-->
            <el-input
              v-model="form.redirect"
              :placeholder="'请输入' + tempDesc.redirect"
            />
          </el-form-item>

          <el-form-item :label="tempDesc.permissionFlag" prop="permissionFlag">
            <!--          <el-input v-model="form.resources" :placeholder="'请输入' + tempDesc.resources" :disabled="dialogStatus !='create'"/>-->
            <el-input
              v-model="form.permissionFlag"
              :placeholder="'请输入' + tempDesc.permissionFlag"
            />
          </el-form-item>

          <el-form-item :label="tempDesc.type" prop="type">
            <el-select
              v-model="form.type"
              class="filter-item"
              :placeholder="'请选择' + tempDesc.type"
              clearable
            >
              <el-option
                v-for="item in menuTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="tempDesc.icon" prop="icon">
            <el-input
              v-model="form.icon"
              :placeholder="'请输入' + tempDesc.icon"
            />
          </el-form-item>
          <el-form-item :label="tempDesc.sortOrder" prop="sortOrder">
            <el-input
              v-model="form.sortOrder"
              type="number"
              :placeholder="'请输入' + tempDesc.sortOrder"
            />
          </el-form-item>
          <!--    是否路由菜单  -->
          <el-form-item :label="tempDesc.route" prop="route">
            <el-switch
              v-model="form.route"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </el-form-item>

          <el-form-item :label="tempDesc.hidden" prop="hidden">
            <el-switch
              v-model="form.hidden"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </el-form-item>

          <el-form-item :label="tempDesc.keepAlive" prop="keepAlive">
            <el-switch
              v-model="form.keepAlive"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </el-form-item>

          <!--        <el-switch-->
          <!--          v-model="value"-->
          <!--          active-color="#13ce66"-->
          <!--          inactive-color="#ff4949"-->
          <!--          active-value="100"-->
          <!--          inactive-value="0">-->
          <!--        </el-switch>-->
          <!--        <el-form-item :label="tempDesc.description" prop="description">-->
          <!--          <el-input v-model="form.description" type="textarea" :rows="7" :placeholder="'请输入' + tempDesc.description"/>-->
          <!--        </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import treeTable from '@/components/TreeTable'
  import { validateCh } from '@/utils/validate'
  import { getAction, postAction, deleteAction, putAction } from '@/api/action'

  const hasButtons = {
    deletebutton: 'sys:menu:delete',
    editbutton: 'sys:menu:edit',
    addsubbutton: 'sys:menu:addsub',
    addbutton: 'sys:menu:add',
  }
  // 常量title
  const tempDesc = {
    id: '',
    parentId: '',
    url: '路径',
    permissionFlag: '权限编码',
    name: '名称',
    // 'level': '级别',
    sortOrder: '排序',
    icon: 'icon',
    type: '类型',
    // 'description': '备注',
    redirect: '默认跳转路径',
    parentName: '上级菜单',
    component: '前端组件',
    route: '是否路由',
    hidden: '隐藏路由',
    keepAlive: '是否缓存',
    alwaysShow: '聚合子路由',
  }
  const menuTypeOptions = [
    { key: 1, display_name: '菜单' },
    { key: 2, display_name: '按钮' },
  ]

  export default {
    // mixins: [BaseListMixin],
    name: 'MenuManagement',
    components: { treeTable },
    data() {
      const _validateCh = (rule, value, callback) => {
        if (!!value && validateCh(value)) {
          callback(new Error('不能包含中文'))
        }
        callback()
      }
      return {
        hasButtons: hasButtons,
        expandAll: true,
        // expandAll: true, // 是否全部展开
        expandAllTitle: '展开全部',
        tempDesc: tempDesc,
        listLoading: true,
        columns: [
          {
            label: tempDesc.name,
            key: 'name',
            width: 220,
            expand: true,
            align: 'left',
            headerAlign: 'center',
          },
          {
            label: tempDesc.url,
            key: 'url',
          },
          {
            label: tempDesc.component,
            key: 'component',
          },
          {
            label: tempDesc.permissionFlag,
            key: 'permissionFlag',
          },
          {
            label: tempDesc.type,
            key: 'type',
          },
          {
            label: tempDesc.icon,
            key: 'icon',
          },
          {
            label: tempDesc.sortOrder,
            key: 'sortOrder',
          },
          // {
          //   label: tempDesc.description,
          //   key: 'description'
          // }
          //          {
          //            label: '操作',
          //            key: 'operation',
          //            width:300
          //          }
        ],
        menuList: [],
        menuTree: [], // 树形菜单
        dialogVisible: false,
        dialogStatus: '',
        titleMap: {
          update: '编辑菜单',
          create: '增加菜单',
        },
        form: {
          id: undefined,
          parentId: undefined,
          url: undefined,
          resources: undefined,
          title: undefined,
          // 'level': undefined,
          sortOrder: undefined,
          icon: undefined,
          type: undefined,
          // 'description': undefined,
          redirect: undefined,
          parentName: undefined,
          component: undefined,
          route: undefined,
          hidden: undefined,
          keepAlive: undefined,
          alwaysShow: undefined,
        },
        modelIcon: {
          //模态框图标
          create: 'el-icon-document-add',
          update: 'el-icon-edit-outline',
          detail: 'el-icon-document-copy',
        },
        menuTypeOptions,
        rules: {
          resources: [
            {
              required: true,
              message: '请输入' + tempDesc.resources,
              trigger: 'blur',
            },
            {
              min: 1,
              max: 100,
              message: '长度在 1 到 100 个字符',
              trigger: 'blur',
            },
            { validator: _validateCh, trigger: 'blur' },
          ],
          title: [
            {
              required: true,
              message: '请输入' + tempDesc.title,
              trigger: 'blur',
            },
            {
              min: 1,
              max: 25,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur',
            },
          ],
          type: [
            {
              required: true,
              message: '请选择' + tempDesc.type,
              trigger: 'blur',
            },
          ],
          sortOrder: [
            {
              required: true,
              message: '请输入' + tempDesc.sortOrder,
              trigger: 'blur',
            },
          ],
          name: [
            {
              required: true,
              message: '请输入' + tempDesc.name,
              trigger: 'blur',
            },
          ],
          component: [
            {
              required: true,
              message: '请输入' + tempDesc.component,
              trigger: 'blur',
            },
          ],
          url: [
            {
              required: true,
              message: '请输入' + tempDesc.url,
              trigger: 'blur',
            },
          ],
          // description: [
          //   {max: 200, message: '长度最多200个字符', trigger: 'blur'}
          // ]
        },
        url: {
          treeMenu: '/presoftasim/system/menu/treeMenu',
          delete: '/presoftasim/system/menu/delete',
          create: '/presoftasim/system/menu/create',
          update: '/presoftasim/system/menu/update',
        },
      }
    },
    created() {
      if (
        this.global_checkBtnPermission([
          'sys:menu:addsub',
          'sys:menu:edit',
          'sys:menu:delete',
        ])
      ) {
        this.columns.push({ label: '操作', key: 'operation', width: 320 })
      }
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        let that = this
        getAction(this.url.treeMenu).then((res) => {
          that.menuList = res.data.menuList
          that.menuTree = res.data.menuTree
          that.listLoading = false
        })
      },
      handleCreate(row) {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogVisible = true

        /*       if (!row) { // 一级菜单
          this.form.level = "1"; // 默认一级菜单
          // this.form.parentId = "0"
        }*/
        if (row) {
          // 子菜单
          // this.form.level = parseInt(row.level) + 1;
          this.form.parentId = row.id
          this.form.parentName = row.name
        }
      },
      handleUpdate(row) {
        this.form = {}
        // this.form = Object.assign({}, row) // copy obj  此方法在这里暂时不能使用，会出错 -> 有多余参数
        let obj = {}
        //  给表单赋值的话，一定要一次性付完,不然会出现奇怪的问题
        obj.id = row.id
        obj.parentId = row.parentId
        obj.name = row.name
        obj.url = row.url
        obj.permissionFlag = row.permissionFlag
        obj.type = row.type
        obj.icon = row.icon
        obj.sortOrder = row.sortOrder
        obj.component = row.component
        obj.hidden = row.hidden
        obj.alwaysShow = row.alwaysShow
        obj.route = row.route
        obj.keepAlive = row.keepAlive
        var parentNode = this.findTreeNode(row.parentId)
        if (parentNode) {
          obj.parentName = parentNode.name
        }
        this.form = Object.assign({}, obj)
        this.dialogStatus = 'update'
        this.dialogVisible = true
      },
      handleDelete(id) {
        // deleteMenu(row.id).then(response => {
        //   if (response.code == 200) {
        //     this.getList()
        //     this.submitOk(response.message)
        //   } else {
        //     this.submitFail(response.message)
        //   }
        // })
        deleteAction(this.url.delete, { id: id }).then((res) => {
          this.getList()
        })
      },
      submitForm() {
        this.form.parentName = undefined
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dialogStatus === 'create') {
              // 新添加
              postAction(this.url.create, this.form).then((res) => {
                this.getList()
                this.dialogVisible = false
              })
            } else {
              // 修改
              putAction(this.url.update, this.form).then((res) => {
                this.getList()
                this.dialogVisible = false
              })
            }
          }
        })
      },
      formatMenuType(row, column) {
        switch (row.type) {
          case 1:
            return '菜单'
            break
          case 2:
            return '按钮'
            break
        }
      },
      findTreeNode(id) {
        let node = this.menuTree.find((item) => {
          return item.id == id
        })
        return node
      },
      handleExpand() {
        this.expandAll = !this.expandAll
        this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
      },
      resetForm() {
        this.form = {
          id: undefined,
          parentId: undefined,
          url: undefined,
          resources: undefined,
          title: undefined,
          level: undefined,
          sortOrder: undefined,
          icon: undefined,
          type: undefined,
          // 'description': undefined,
          parentName: undefined,
          component: undefined,
          route: true,
          hidden: false,
          keepAlive: false,
        }
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  .el-form .el-select {
    width: 100%;
  }
</style>
